package com.ellfors.module_first.compose_test

import android.content.Intent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ellfors.common.base.BaseComposeActivity
import com.ellfors.common.ext.clickNoShadow
import com.ellfors.common.ext.observe
import com.ellfors.common.ext.observeOnState
import com.ellfors.common.ext.logD

/**
 * 测试Compose与ViewModel联动
 * @property mViewModel TestComposeViewModel
 */
class TestComposeActivity : BaseComposeActivity() {

    companion object {
        fun start(activity: AppCompatActivity) {
            Intent(activity, TestComposeActivity::class.java).apply {
                activity.startActivity(this)
            }
        }
    }

    private val mViewModel by viewModels<TestComposeViewModel>()

    override fun initData() {
        showTitleBar("测试Compose")

        mViewModel.successEvent.observe(this) {
            "[Success] $it".logD()
        }
        mViewModel.errorEvent.observeOnState(this) {
            "[Error] $it".logD()
        }
        mViewModel.startEvent.observe(this) {
            "[Start] $it".logD()
        }
        mViewModel.completeEvent.observe(this) {
            "[Complete] $it".logD()
        }
    }

    @Composable
    override fun InitCompose() {
        Page(responseValue = mViewModel.errorState.value)
    }

    @Preview
    @Composable
    private fun Page(responseValue: String = "Null") {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "SecondActivity Click Back", Modifier.clickNoShadow {
                finish()
            })
            Spacer(Modifier.height(30.dp))
            Button(onClick = {
                testLogin()
            }) {
                Text(text = "TestLogin")
            }
            Spacer(modifier = Modifier.height(10.dp))
            Text(text = responseValue)
        }
    }

    private fun testLogin() {
        mViewModel.doLogin(
            "123",
            "123"
        )
    }
}